﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MapNavAgent : MonoBehaviour {

    private float speed = 0.0f;
    private Vector3[] roadData = null;

    private int nextStep = 1; // 
    private float vx;
    private float vy;
    private float vz;
    private float walkTime = 0.0f;
    private float passedTime = 0.0f;
    private bool isWalking = false;

    Quaternion dstRot;
    
    public void InitMapNavAgent(float speed) {
        this.speed = speed;
    }

    public void NavOnRoad(Vector3[] roadData) {
        this.roadData = roadData;

        this.isWalking = false;
        if (this.roadData == null || this.roadData.Length < 2) {
            return;
        }

        this.transform.localPosition = this.roadData[0];
        this.nextStep = 1;
        this.MoveToNext();
    }

    private void MoveToNext() { // 从当前点---->this.roadData[this.nextStep]
        if (this.nextStep >= this.roadData.Length) { // 走完了;
            this.isWalking = false;
            return;
        }

        Vector3 src = this.transform.localPosition;
        Vector3 dst = this.roadData[this.nextStep];

        Vector3 dir = dst - src;
        float len = dir.magnitude;

        this.vx = this.speed * dir.x / len;
        this.vy = this.speed * dir.y / len;
        this.vz = this.speed * dir.z / len;

        this.walkTime = len / this.speed;
        this.passedTime = 0;

        this.isWalking = true;

        Quaternion old = this.transform.rotation;
        this.transform.LookAt(dst); // 当前得方向 ----> 目标方向;
        this.dstRot = this.transform.rotation;
        this.transform.rotation = old;

    }

    public void StopNav() {
        this.isWalking = false;
    }

	void Update () {
        if (!this.isWalking) {
            return;
        }

        float dt = Time.deltaTime;
        this.passedTime += dt;
        if (this.passedTime > this.walkTime) { 
            dt -= (this.passedTime - this.walkTime);
        }

        Vector3 pos = this.transform.localPosition;
        pos.x += (this.vx * dt);
        pos.y += (this.vy * dt);
        pos.z += (this.vz * dt);
        this.transform.localPosition = pos;


        // 四元数得球面插值;
        Quaternion now = Quaternion.Slerp(this.transform.rotation, this.dstRot, 10.0f * dt);
        this.transform.rotation = now;
        // end 

        if (this.passedTime >= this.walkTime) {
            this.nextStep++;
            this.MoveToNext();
        }

	}
}
